﻿using AutoMapper.Internal.Mappers;
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using IntelligentAgriculture.Contracts.Interface;
using IntelligentAgriculture.Domain.Interface;
using IntelligentAgriculture.Domain.Entity;
using Microsoft.Extensions.Logging;
using IntelligentAgriculture.Contracts.Dto.Input;
using JetBrains.Annotations;
using IntelligentAgriculture.Domain;
using System.Transactions;
using NPOI.SS.Formula.Functions;

namespace IntelligentAgriculture.Services
{
    public class UserService : IUserService
    {
        private readonly IUserRepository _userRepository;
        private readonly ILogger<UserService> _logger;
        private readonly IMapper _mapper;
        private readonly AgricultureDbContext _dbcontext;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userRepository"></param>
        /// <param name="logger"></param>

        public UserService(IUserRepository userRepository, ILogger<UserService> logger, IMapper mapper, AgricultureDbContext dbcontext)
        {
            _userRepository = userRepository;
            _logger = logger;
            _mapper = mapper;
            _dbcontext = dbcontext;
        }
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns>获取用户信息</returns>
        public List<Userinfo> GetUsers()
        {
            // 拿到所有的用户（）
            // select * from users;
            var query = _userRepository.GetUsers()/*.Where(p=>p.IsDeleted==false)*/ .AsNoTracking();
            return query.ToList();
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="UserName">用户名</param>
        /// <param name="PassWord">密码</param>
        /// <returns>返回登录信息</returns>
        public Userinfo Login(string UserName, string PassWord)
        {
            var user = _userRepository.Login(UserName, PassWord);
            return user;
        }
        /// <summary>
		/// 新增人员信息
		/// </summary>
		/// <param name="info">人员信息</param>
		/// <returns></returns>
		public async Task<int> AddUser(AddUserInput input)
        {
            using (var tran = _dbcontext.Database.BeginTransaction())
            {
                try
                {
                    //添加用户信息
                    var user = new Userinfo()
                    {
                        Uname = input.Uname,
                        Upwd = input.Upwd,
                        Sex = input.Sex,
                        CardNumber = input.CardNumber,
                        CardType = input.CardType,
                        EducationBackground = input.EducationBackground,
                        Email = input.Email,
                        GraduateInstitutions = input.GraduateInstitutions,
                        Name = input.Name,
                        NickName = input.Name,
                        PartMent = input.PartMent,
                        Phone = input.Phone,
                    };
                    //_mapper.Map<AddUserInput>(user);
                    //添加用户信息
                    await _dbcontext.Userinfos.AddAsync(user);
                    //添加入职信息表
                    var userWork = new Entryinformation()
                    {
                        DepartmentId = input.DepartmentId,
                        EmployeeStatus = input.EmployeeStatus,
                        EntryInformationId = input.EntryInformationId,
                        HireDate = input.HireDate,
                        JobTitle = input.JobTitle,
                        PersonnelLevel = input.PersonnelLevel,
                        Position = input.Position,
                        RegularizationDate = input.RegularizationDate,
                        UnitId = input.UnitId,
                        UserId = user.Uid,
                    };
                    //_mapper.Map<AddUserInput>(userWork);
                    //添加入职信息表
                    await _dbcontext.Entryinformations.AddAsync(userWork);
                    //添加用户角色表
                    var userRole = new Userrole()
                    {
                        Uid = user.Uid,
                        Rid = input.Rid
                    };
                    //_mapper.Map<AddUserInput>(userRole);
                    //添加用户角色表
                    await _dbcontext.Userroles.AddAsync(userRole);
                    //提交数据库
                    await _dbcontext.SaveChangesAsync();
                    //提交事务
                    tran.Commit();
                    return 1;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    _logger.LogError("新增人员信息失败：" + ex.Message);
                    throw;
                }
            }
        }
    }
}